<?php
namespace App\Http\Controllers\Api\Mall;

use App\Http\Controllers\Api\Third\WechatController;
use App\Http\Controllers\Controller;
use App\Models\Mall\Goods;
use App\Models\Mall\Order;
use App\Models\Mall\OrderItem;
use App\Tools\User\User;
use App\UserCoinLog;
use EasyWeChat\Payment\Order as WMOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PayController extends Controller
{
    const business_id = 7;  //商城

    protected $request;

    //兑换
    public function exchange(Request $request)
    {
        $this->request = $request;
        $goods_id = $request->input('goods_id');
        $coupon_code = $request->input('coupon_code');//优惠劵编码
        $pay_type = $request->input('pay_type');//支付类型  1.小妖币 2.优惠卷 3.微信支付
        $type = $request->input('type', 'JSAPI');
        $user = auth()->user();

        //支付类型
        $type_pay_arr = [
            1 => 1,
            2 => 2,
            3 => 3,
        ];
        if (!in_array($pay_type, $type_pay_arr)) {
            return $this->genRet(1002, '非法支付方式');
        }

        $goods = Goods::findOrFail($goods_id);
        $order_id = date('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);

        try {
            DB::beginTransaction();

            $quantity = 1; //兑换一个
            $xyb = $goods->need_xyb / 100 * $quantity;
            $jb = $goods->need_jb;
            $userTotalXyb = UserCoinLog::totalXyb($user->id);
            $userTotalJb = UserCoinLog::totalJb($user->id);
            if ($userTotalJb < $jb) {
                DB::rollBack();
                return $this->genRet(1002, '金币不够兑换');
            }

            //扣除用户金币
            $key = self::business_id . '-' . UserCoinLog::TYPE_JB . '-' . $user->id . '-' . time();
            UserCoinLog::log(self::business_id, $user->id, UserCoinLog::TYPE_JB, -$jb, '商城金币兑换' . $goods->name, $key);

            $order = new Order();
            $order->trade_id = $order_id;
            $order->user_id = $user->id;
            $order->status = 0;
            $order->ukey = $order_id;
            $order->save();

            //支付方式
            switch ($pay_type) {
                case 1://小妖币
                    if ($xyb < 0) {
                        DB::rollBack();
                        return $this->genRet(1002, '小妖币错误');
                    }
                    if ($userTotalXyb < $xyb) {
                        DB::rollBack();
                        return $this->genRet(1002, '小妖币不够兑换');
                    }
                    //先扣除用户小妖币，一个用户一秒不能重复兑换多次
                    $key = self::business_id . '-' . UserCoinLog::TYPE_XYB . '-' . $user->id . '-' . time();
                    UserCoinLog::log(self::business_id, $user->id, UserCoinLog::TYPE_XYB, -$xyb, '商城小妖币兑换' . $goods->name, $key);
                    break;
                case 2://优惠卷
                    //是否有使用优惠卷功能
                    if (!empty($coupon_code)) {
                        $userTool = new User();
                        $coupon_id = 0;
                        $xyb = $userTool->getCouponXyb($coupon_code, $xyb, $goods_id, $order_id, $coupon_id);
                        if ($xyb < 0) {
                            DB::rollBack();
                            return $this->genRet(1002, '该优惠卷不存在!');
                        }
                        $order->ukey = $pay_type . '-' . $coupon_id;
                    } else {
                        DB::rollBack();
                        return $this->genRet(1002, '没有优惠卷编码');
                    }
                    break;
                case 3: //微信支付
                    $wechat = new  WechatController();
                    $payData = $wechat->goodsPay($user, $order, $goods, $type);
                    $payArr = json_decode($payData, true);
                    if ($payArr['code'] != 1000) {
                        DB::rollBack();
                        return $this->genRet(1002, '创建订单失败！');
                    }
                    break;
                default:
                    DB::rollBack();
                    return $this->genRet(1002, '非法支付方式');
                    break;

            }

            $orderItem = new OrderItem();
            $orderItem->order_id = $order->id;
            $orderItem->goods_id = $goods_id;
            $orderItem->price = $goods->price;
            $orderItem->original_price = $goods->original_price;
            $orderItem->quantity = $quantity;
            $orderItem->xyb = $goods->need_xyb;
            $orderItem->save();

            switch ($pay_type) {
                case 1:
                case 2:
                    //再判断用户总小妖币是否小于0，小于的时候回滚
                    if ($pay_type == 1) {
                        $userTotalXyb = UserCoinLog::totalXyb($user->id);
                        if ($userTotalXyb < 0) {
                            DB::rollBack();
                            return $this->genRet(1002, '小妖币不够兑换');
                        }
                    }
                    break;
                case 3:
                    break;
            }

            $userTotalJb = UserCoinLog::totalJb($user->id);
            if ($userTotalJb < 0) {
                DB::rollBack();
                return $this->genRet(1002, '金币不够兑换');
            }

            if (in_array($pay_type, array(1, 2))) {
                $order->status = 1;
                $order->save();
                DB::commit();
            }

            if ($pay_type == 3) {
                DB::commit();
                return response()->json($payArr);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->genRet(1003, '网络繁忙，请稍候再试');
        }

        return $this->genRet(1000, '兑换成功');
    }

    private function genRet($code, $msg, $data = [])
    {
        return response()->json(['code' => $code, 'msg' => $msg, 'data' => $data]);
    }
}